package com.example.controller;

import com.example.domain.dto.result.ProductResult;
import com.example.domain.entity.Product;
import com.example.service.impl.ProductServiceImpl;
import com.example.domain.query.ProductQuery;
import com.example.factory.ResultFactory;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
import io.swagger.v3.oas.annotations.Operation;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author baomidou
 * @since 2025-05-07
 */
@CrossOrigin
@RestController
@RequestMapping("/product")
@Tag(name = "产品管理器")
public class ProductController {
    @Autowired
    private ProductServiceImpl productService;

    @Autowired
    private ResultFactory resultFactory;

    @GetMapping("/list")
    @Operation(summary = "获取产品列表")
    public List<ProductResult> list() {
        return productService.list().stream().map(resultFactory::convert).toList();
    }

    @PostMapping("/page")
    @Operation(summary = "分页查询产品")
    public IPage<ProductResult> pageQuery(@RequestBody ProductQuery query,
                                    @RequestParam(defaultValue = "1") int pageNum,
                                    @RequestParam(defaultValue = "10") int pageSize) {
        return resultFactory.convertProductPage(productService.pageQuery(query, pageNum, pageSize));
    }

    @PostMapping("/save")
    @Operation(summary = "保存产品")
    public boolean save(@RequestBody Product product) {
        return this.productService.save(product);
    }

    @PostMapping("/update")
    @Operation(summary = "更新产品")
    public boolean update(@RequestBody Product product) {
        return this.productService.updateById( product);
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除产品")
    public void deleteById(@PathVariable int id) {
        if (!this.productService.removeById(id)) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "删除失败，人员不存在");
        }
    }
}
